<template>
  <Dialog title="报工" v-model="dialogVisible" width="60%">
    <el-button @click="addCol" type="primary" :disabled="formLoading">新增行</el-button>
    <el-table
      ref="singleTableRef"
      :data="formData.courseWorks"
      v-loading="formLoading"
      style="width: 100%"
      class="mt-10px"
      border
      :height="300"
      :summary-method="getSummaries"
      show-summary
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column
        :prop="item.val"
        :label="item.label"
        :min-width="200"
        align="center"
        :key="index"
        v-for="(item, index) in tableTitle"
      >
        <template #default="scope">
          <!-- 如果是新增数据 -->
          <template v-if="item.val == 'jobNumber'">
            <el-select
              v-model="scope.row[item.val]"
              v-if="scope.row.isAdd"
              filterable
              remote
              reserve-keyword
              :remote-method="getJobNumberList"
              :loading="jobNumberLoading"
              placeholder=""
              @change="
                (e) => {
                  changeJobPerson(e, scope.$index)
                }
              "
            >
              <el-option
                v-for="dict in jobNumberList"
                :key="dict.jobNumber"
                :label="dict.jobNumber"
                :value="dict.jobNumber"
              />
            </el-select>
            <template v-else>{{ scope.row[item.val] }}</template>
          </template>
          <template v-else-if="item.val == 'reportWorkRatio'">
            <el-input
              v-model="scope.row[item.val]"
              type="number"
              @input="
                (e) => {
                  changeReportWorkRatio(e, scope.$index)
                }
              "
            />
          </template>
          <template v-else>{{ scope.row[item.val] }}</template>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="closeView">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
  import * as componentApi from '@/api/componentApi'
  import request from '@/config/axios'
  const message = useMessage() // 消息弹窗

  const dialogVisible = ref(false) // 弹窗的是否展示
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const submitUrl = ref('') //报工请求地址
  const formData = reactive({
    id: undefined,
    dictProcessName: undefined,
    courseWorks: [],
    reportQuantity: undefined,
    completeQuantity: undefined,
    planQuantity: undefined,
    dictReportWay: undefined,
    differenceQuantity: undefined,
    processPrice: undefined,
    childList: [],
    parentId: undefined
  })
  const processPrice = ref(0) //报工单价
  const basicPrice = ref(0) //加工单价 * 工序报工占比
  /** 打开弹窗
   * res:操作数据
   * url：请求地址
   * childList：项目单价数据
   *
   */
  const open = async (res: object, url: string, planQuantity: number,  childList?: Array) => {
    dialogVisible.value = true
    let data = JSON.parse(JSON.stringify(res))
    //个人加工价格 = 加工单价 * 工序报工占比 * 个人报工占比
    //dictReportWay: 10 计件
    if (data.dictReportWay == 20) {
      data.reportQuantity = (parseFloat(data.reportQuantity) / 100).toFixed(4)
      basicPrice.value = (data.processPrice * data.reportQuantity * planQuantity).toFixed(4)
    } else {
      basicPrice.value = (data.processPrice * data.reportQuantity).toFixed(4)
    }
    data.operatorSimpleList.map((item) => {
      item.reportWorkRatio = parseFloat(100 / data.operatorSimpleList.length).toFixed(2)
      item.processlPrice = (basicPrice.value * (item.reportWorkRatio / 100)).toFixed(4)
      item.isAdd = false
    })
    processPrice.value = data.processPrice
    formData.courseWorks = data.operatorSimpleList
    formData.dictProcessName = data.dictProcessName
    formData.id = res['id']
    formData.parentId = res['parentId']
    formData.completeQuantity = res['completeQuantity']
    formData.reportQuantity = res['reportQuantity']
    formData.planQuantity = res['planQuantity']
    formData.dictReportWay = res['dictReportWay']
    formData.differenceQuantity = res['differenceQuantity']
    formData.processPrice = res['processPrice']
    formData.childList = childList
    submitUrl.value = url
  }
  defineExpose({ open }) // 提供 open 方法，用于打开弹窗

  /**修改占比 */
  const changeReportWorkRatio = (val: number, index: number) => {
    formData.courseWorks[index].processlPrice = parseFloat(
      basicPrice.value * (parseFloat(val || 0) / 100)
    ).toFixed(4)
  }
  /**修改员工 */
  const changeJobPerson = (val, index: number) => {
    const name = jobNumberList.value.filter((item) => item.jobNumber == val)[0].staffName
    formData.courseWorks[index].staffName = name
  }
  /**获取员工工号 */
  const jobNumberLoading = ref(false) //加载中
  const jobNumberList = ref([])
  const getJobNumberList = async (keyword: string) => {
    if (keyword != '') {
      jobNumberLoading.value = true
      const data = await componentApi.getStaffList(keyword)
      jobNumberList.value = data
      jobNumberLoading.value = false
    }
  }

  /**合计 */
  const getSummaries = (param) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '合计'
        return
      }
      if (['reportWorkRatio', 'processlPrice'].includes(column.property)) {
        let maxNum = column.property == 'processlPrice' ? 4 : 2
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => Number.isNaN(value))) {
          sums[index] = `${values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!Number.isNaN(value)) {
              let res = (parseFloat(prev) + parseFloat(curr)).toFixed(maxNum)
              return res
            } else {
              let res = parseFloat(prev).toFixed(maxNum)
              return res
            }
          }, 0)}`
        } else {
          sums[index] = 'N/A'
        }
      }
    })

    return sums
  }
  /** 提交表单 */
  const tableTitle = ref([
    {
      label: '员工工号',
      val: 'jobNumber'
    },
    {
      label: '员工名称',
      val: 'staffName'
    },
    {
      label: '本次报工占比(%)',
      val: 'reportWorkRatio'
    },
    {
      label: '加工价格',
      val: 'processlPrice'
    }
  ])
  const submitForm = async () => {
    const data = JSON.parse(JSON.stringify(formData))
    let num = 0
    let flag = false
    data.courseWorks.map((item) => {
      num += parseFloat(item.reportWorkRatio || 0)
      if (['', undefined, null].includes(item.jobNumber)) flag = true
    })
    if (flag) {
      message.error('员工不能为空')
      return
    }
    if (num != 100) {
      message.error('本次报工占比之和必须为100!')
      return
    }
    try {
      formLoading.value = true
      await request.put({ url: submitUrl.value, data })
      message.success('报工成功')
      closeView()
    } finally {
      formLoading.value = false
    }
  }

  /**新增行 */
  const addCol = () => {
    formData.courseWorks.push({
      jobNumber: undefined,
      staffName: undefined,
      reportWorkRatio: 0,
      processlPrice: undefined,
      isAdd: true
    })
  }

  /**关闭 */
  const emit = defineEmits(['refresh']) // 定义 success 事件，用于操作成功后的回调
  const closeView = () => {
    emit('refresh')
    dialogVisible.value = false
  }
</script>